<?php

namespace app\common\service;

use GuzzleHttp\Client;
use think\Exception;

class EthereumService
{
    // ✅ 改为 Etherscan 的 URL 和参数风格
    const API_URL = 'https://api.etherscan.io/v2/api';

    protected $client;
    protected $apiKey;
    protected $chainId;

    public function __construct()
    {
        // 🔑 强制使用你提供的 API Key
        $this->apiKey  = '6NBBQUXYQ4P97RHHRDNF6PHQB58XJXC8T9';
        $this->chainId = '56'; // BSC chainId

        // 🚀 使用通用 HTTP 客户端（GET 请求）
        $this->client = new Client([
            'timeout' => 30,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (compatible; TransactionValidator/1.0)'
            ]
        ]);
    }

    /**
     * 验证交易是否成功 —— 现在改为调用 etherscan 的 txlistinternal
     *
     * @param string $txHash 交易哈希
     * @return array
     */
    public function isTransactionSuccessful($txHash)
    {
        if (!is_string($txHash) || !preg_match('/^0x[a-fA-F0-9]{64}$/', $txHash)) {
            return [
                'success' => false,
                'message' => 'Invalid transaction hash format.'
            ];
        }

        try {
            // 📡 发起 GET 请求，完全匹配你的 cURL
            $response = $this->client->get(self::API_URL, [
                'query' => [
                    'apikey'  => $this->apiKey,
                    'chainid' => $this->chainId,
                    'module'  => 'account',
                    'action'  => 'txlistinternal',
                    'txhash'  => $txHash
                ]
            ]);

            $body = $response->getBody()->getContents();
            $data = json_decode($body, true);

            // ⚠️ 注意：Etherscan 可能返回错误或空结果，因为不支持 chainid=56
            if (!isset($data['status']) || $data['status'] !== '1') {
                $message = $data['message'] ?? 'Unknown error or chain not supported';
                return [
                    'success' => false,
                    'message' => $message,
                    'raw' => $data
                ];
            }

            $result = $data['result'];

            if (empty($result)) {
                return [
                    'success' => false,
                    'message' => 'No internal transactions found for this hash.'
                ];
            }

            // ✅ 假设只要返回了数据，就认为“成功”（按你逻辑）
            return [
                'success' => true,
                'message' => 'Internal transactions fetched.',
                'data' => $result // 返回内部交易列表
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Network error: ' . $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ];
        }
    }

    // ======================
    // 以下方法保留但不再使用
    // ======================

    protected function getTransactionByHash($txHash) { return null; }
    protected function weiToEther($wei) { return null; }
    protected function getConfirmations($blockNumber) { return null; }
}